package com.beemans.corekit.helper;

import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.RemoteViews;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.NotificationCompat;

import com.beemans.corekit.R;
import com.beemans.corekit.constant.AppConstant;
import com.beemans.corekit.constant.ReportEventConstants;
import com.beemans.corekit.data.PushContent;
import com.beemans.corekit.data.PushLayout;
import com.beemans.corekit.data.RemotePushEntity;
import com.beemans.corekit.integration.language.MultiLanguages;
import com.beemans.corekit.ui.activity.NotificationActivity;
import com.beemans.corekit.utils.CacheUtils;
import com.beemans.corekit.utils.PermissionUtils;
import com.beemans.corekit.utils.ReportUtils;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;

import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.Random;

public class NotificationHelper {
    private static final Random RANDOM = new Random();

    private static final class Holder {
        private static final NotificationHelper INSTANCE = new NotificationHelper();
    }

    public static NotificationHelper getInstance() {
        return Holder.INSTANCE;
    }

    private final int[] progressBarIds = new int[]{
            R.id.notification_progressBar_0,
            R.id.notification_progressBar_1,
            R.id.notification_progressBar_2,
            R.id.notification_progressBar_3
    };

    /**
     * 展示远程推送通知
     */
    public void showRemoteNotification(
            @NonNull Context context,
            @NonNull Map<String, String> customData
    ) {
        if (customData.isEmpty()) {
            return;
        }
        if (!PermissionUtils.areNotificationsEnabled()) {
            return;
        }

        final NotificationManager notificationManager =
                (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        if (notificationManager == null) {
            return;
        }

        final RemotePushEntity entity = new RemotePushEntity();
        Locale locale;
        try {
            locale = MultiLanguages.getSystemLanguage(context);
        } catch (Throwable throwable) {
            locale = Locale.getDefault();
        }
        if (locale != null) {
            entity.locale = locale.toString();
            entity.country = locale.getCountry();
        }

        if (customData.containsKey(AppConstant.REMOTE_PUSH_ID)) {
            try {
                final String remotePushId = customData.get(AppConstant.REMOTE_PUSH_ID);
                if (!TextUtils.isEmpty(remotePushId)) {
                    entity.pushId = Integer.parseInt(remotePushId);
                }
            } catch (Throwable ignored) {
            }
        }
        if (customData.containsKey(AppConstant.REMOTE_PUSH_DATE)) {
            entity.pushDate = customData.get(AppConstant.REMOTE_PUSH_DATE);
        }
        if (customData.containsKey(AppConstant.REMOTE_PUSH_TITLE)) {
            entity.title = customData.get(AppConstant.REMOTE_PUSH_TITLE);
        }
        if (customData.containsKey(AppConstant.REMOTE_PUSH_BODY)) {
            entity.body = customData.get(AppConstant.REMOTE_PUSH_BODY);
        }
        if (customData.containsKey(AppConstant.REMOTE_PUSH_IMAGE_URL)) {
            entity.imgUrl = customData.get(AppConstant.REMOTE_PUSH_IMAGE_URL);
        }
        if (customData.containsKey(AppConstant.REMOTE_PUSH_BUTTON_TEXT)) {
            entity.btnText = customData.get(AppConstant.REMOTE_PUSH_BUTTON_TEXT);
        }
        if (customData.containsKey(AppConstant.REMOTE_PUSH_BUTTON_LINK)) {
            entity.btnLink = customData.get(AppConstant.REMOTE_PUSH_BUTTON_LINK);
        }
        if (customData.containsKey(AppConstant.REMOTE_PUSH_BUTTON_TYPE)) {
            try {
                final String remoteBtnType = customData.get(AppConstant.REMOTE_PUSH_BUTTON_TYPE);
                if (!TextUtils.isEmpty(remoteBtnType)) {
                    entity.btnType = Integer.parseInt(remoteBtnType);
                }
            } catch (Throwable ignored) {
            }
        }

        if (TextUtils.isEmpty(entity.title)
                || TextUtils.isEmpty(entity.body)
                || TextUtils.isEmpty(entity.btnText)
        ) {
            return;
        }

        final boolean onlyTitle = Objects.equals(entity.title, entity.body);
        if (onlyTitle) {
            entity.body = "";
        }

        //noinspection deprecation
        Glide.with(context)
                .asBitmap()
                .load(entity.imgUrl)
                .into(new SimpleTarget<Bitmap>() {
                    @Override
                    public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                        try {
                            showRemoteNotification(context, notificationManager, resource, entity);
                        } catch (Exception ignored) {
                        }
                    }

                    @Override
                    public void onLoadFailed(@Nullable Drawable errorDrawable) {
                        try {
                            showRemoteNotification(context, notificationManager, null, entity);
                        } catch (Exception ignored) {
                        }
                    }
                });
    }

    private void showRemoteNotification(
            @NonNull Context context,
            @NonNull NotificationManager notificationManager,
            @Nullable Bitmap iconBitmap,
            @NonNull RemotePushEntity entity
    ) {
        Log.e("susu", "showRemoteNotification --- entity:" + entity);

        try {
            //推送的布局
            final boolean onlyTitle = TextUtils.isEmpty(entity.body);
            final PushLayout pushLayout = PushLayout.getPushLayout(onlyTitle);

            // 折叠视图
            final RemoteViews collapsedView = new RemoteViews(context.getPackageName(), pushLayout.collapsedLayout);
            updateRemoteViews(collapsedView, iconBitmap, entity.title, entity.body, entity.btnText, entity.btnType);

            // 展开视图
            final RemoteViews expandedView = new RemoteViews(context.getPackageName(), pushLayout.expandedLayout);
            updateRemoteViews(expandedView, iconBitmap, entity.title, entity.body, entity.btnText, entity.btnType);

            // 头部视图
            final RemoteViews headView = new RemoteViews(context.getPackageName(), pushLayout.headLayout);
            updateRemoteViews(headView, iconBitmap, entity.title, entity.body, entity.btnText, entity.btnType);

            final Intent intent = new Intent(context, NotificationActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            intent.putExtra(AppConstant.REMOTE_PUSH_ENTITY, entity);

            final int requestCode = RequestCodeHelper.getInstance().getRequestCode();
            final PendingIntent pendingIntent = PendingIntent.getActivity(
                    context,
                    requestCode,
                    intent,
                    PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE
            );
            final String channelId = context.getPackageName() + "_remote";
            NotificationChannel notificationChannel = notificationManager.getNotificationChannel(channelId);
            if (notificationChannel == null) {
                notificationChannel = new NotificationChannel(channelId, channelId, NotificationManager.IMPORTANCE_HIGH);
                notificationManager.createNotificationChannel(notificationChannel);
            }

            final int notifyId = CacheUtils.getLocalPushNotifyId();
            final NotificationCompat.Builder notificationBuilder =
                    new NotificationCompat.Builder(context, channelId)
                            .setSmallIcon(R.mipmap.ic_launcher)
                            .setOngoing(false)
                            .setAutoCancel(true)
                            .setGroupSummary(false)
                            .setGroup(String.valueOf(notifyId))
                            .setContent(collapsedView)
                            .setCustomContentView(collapsedView)
                            .setCustomBigContentView(expandedView)
                            .setCustomHeadsUpContentView(headView)
                            .setStyle(new NotificationCompat.DecoratedCustomViewStyle())
                            .setContentIntent(pendingIntent);

            notificationManager.notify(notifyId, notificationBuilder.build());

            ReportUtils.reportRemotePushEvent(ReportEventConstants.REMOTE_PUSH_SHOW, entity);
        } catch (Throwable ignored) {
        }
    }

    /**
     * 展示本地通知
     */
    public void showLocalNotification(@NonNull Context context) {
        try {
            if (!PermissionUtils.areNotificationsEnabled()) {
                return;
            }

            final NotificationManager notificationManager =
                    (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
            if (notificationManager == null) {
                return;
            }

            final String contentTitle = context.getString(PushContent.CONTENT.titleRes);
            final String btnText = context.getString(PushContent.CONTENT.btnRes);
            final int imageRes = PushContent.CONTENT.iconRes;

            final String contentBody;
            if (RANDOM.nextBoolean()) {
                contentBody = context.getString(PushContent.CONTENT.descRes);
            } else {
                contentBody = "";
            }

            final int btnColorType = RANDOM.nextInt(4);

            //推送的布局
            final boolean onlyTitle = TextUtils.isEmpty(contentBody);
            final PushLayout pushLayout = PushLayout.getPushLayout(onlyTitle);

            Bitmap iconBitmap = null;
            try {
                iconBitmap = BitmapFactory.decodeResource(context.getResources(), imageRes);
            } catch (Throwable ignored) {
            }

            // 折叠视图
            final RemoteViews collapsedView = new RemoteViews(context.getPackageName(), pushLayout.collapsedLayout);
            updateRemoteViews(collapsedView, iconBitmap, contentTitle, contentBody, btnText, btnColorType);

            // 展开视图
            final RemoteViews expandedView = new RemoteViews(context.getPackageName(), pushLayout.expandedLayout);
            updateRemoteViews(expandedView, iconBitmap, contentTitle, contentBody, btnText, btnColorType);

            // 头部视图
            final RemoteViews headView = new RemoteViews(context.getPackageName(), pushLayout.headLayout);
            updateRemoteViews(headView, iconBitmap, contentTitle, contentBody, btnText, btnColorType);

            final Intent intent = new Intent(context, NotificationActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

            final int requestCode = RequestCodeHelper.getInstance().getRequestCode();
            final PendingIntent pendingIntent = PendingIntent.getActivity(
                    context,
                    requestCode,
                    intent,
                    PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE
            );
            final String channelId = context.getPackageName() + "_local";
            NotificationChannel notificationChannel = notificationManager.getNotificationChannel(channelId);
            if (notificationChannel == null) {
                notificationChannel = new NotificationChannel(channelId, channelId, NotificationManager.IMPORTANCE_HIGH);
                notificationManager.createNotificationChannel(notificationChannel);
            }

            final int notifyId = CacheUtils.getLocalPushNotifyId();
            final NotificationCompat.Builder notificationBuilder =
                    new NotificationCompat.Builder(context, channelId)
                            .setSmallIcon(R.mipmap.ic_launcher)
                            .setOngoing(false)
                            .setAutoCancel(true)
                            .setGroupSummary(false)
                            .setGroup(String.valueOf(notifyId))
                            .setContent(collapsedView)
                            .setCustomContentView(collapsedView)
                            .setCustomBigContentView(expandedView)
                            .setCustomHeadsUpContentView(headView)
                            .setStyle(new NotificationCompat.DecoratedCustomViewStyle())
                            .setContentIntent(pendingIntent);

            notificationManager.notify(notifyId, notificationBuilder.build());
        } catch (Throwable ignored) {
        }
    }

    /**
     * @noinspection SameParameterValue
     */
    private void updateRemoteViews(
            @NonNull RemoteViews remoteViews,
            @Nullable Bitmap iconBitmap,
            @NonNull String contentTitle,
            @NonNull String contentBody,
            @NonNull String btnText,
            int btnType
    ) {
        // 图片
        remoteViews.setImageViewBitmap(R.id.notification_image, iconBitmap);

        // 标题
        remoteViews.setTextViewText(R.id.notification_title, contentTitle);

        //详情
        if (!TextUtils.isEmpty(contentBody)) {
            remoteViews.setTextViewText(R.id.notification_desc, contentBody);
        }

        // 按钮
        remoteViews.setTextViewText(R.id.notification_button, btnText);

        final int visibleIndex = (btnType >= 0 && btnType < progressBarIds.length) ? btnType : 0;

        for (int i = 0; i < progressBarIds.length; i++) {
            final int visibility = i == visibleIndex ? View.VISIBLE : View.INVISIBLE;
            remoteViews.setViewVisibility(progressBarIds[i], visibility);
        }
    }
}